<?php


class DocumentTable extends Doctrine_Table
{
    public static function getInstance()
    {
        return Doctrine_Core::getTable('Document');
    }
    
    /**
     * @param $document_id - must be != null
     * @return Doctrine_Collection
     */
    static public function findDocumentById($document_id)
    {
        return DocumentTable::getInstance()
            ->find($document_id);
    }
    
    /**
     * @return Doctrine_Collection - all documents which has not been deleted(is_deleted=false). 
     * Result collection is ordered by category_id.
     */
    static public function findAllExistingDocumentsOrderedByCategories()
    {
        return DocumentTable::getInstance()
            ->createQuery('d')
            ->select('d.*')
            ->where("d.is_deleted=?", false)
            ->orderBy('d.category_id ASC')
            ->execute();
    }


    static public function getLuceneIndex()
    {
      ProjectConfiguration::registerZend();

      if (file_exists($index = self::getLuceneIndexFile()))
      {
        return Zend_Search_Lucene::open($index);
      }
      else
      {
        return Zend_Search_Lucene::create($index);
      }
    }

    static public function getLuceneIndexFile()
    {
      return sfConfig::get('sf_data_dir').'/document.'.sfConfig::get('sf_environment').'.index';
    }

    public function getPreparedSearchQueryStr($query)
    {
        $result = preg_match_all('/[^\s]+/',$query,$found);
        $str = $found[0][0]."*";
        for($i=1;$i<count($found[0]);++$i)
        {
            $str = $str.$found[0][$i]."*";
        }
        return $str;
    }

    public function getForLuceneQuery($query,$parameters)
    {
      $first = false;
      $query = $this->getPreparedSearchQueryStr($query);
      $queryStr = $query;

      for(Reset($parameters);$k=key($parameters);Next($parameters))
      {
          if($parameters[$k]=="true")
          {
              if($first==false)
              {
                  $first=true;
                  $queryStr = $k.':'.$query;
              }
              else
              {
                  $queryStr = $queryStr.' OR '.$k.':'.$query;
              }
          }
      }
      if (!$first)
      {
          return null;
      }
      $hits = $this->getLuceneIndex()->find($queryStr);
      $pks = array();
      foreach ($hits as $hit)
      {
        $pks[] = $hit->pk;
      }

      if (empty($pks))
      {
        return array();
      }

      $q = $this->createQuery('j')
        ->whereIn('j.id', $pks)
        ->orderBy('j.category_id ASC')
        ->limit(20);

      return $q->execute();
    }

    static public function getDocumentByIdQuery($document_id)
    {
        return DocumentTable::getInstance()
          ->createQuery('d')
          ->select('d.*')
          ->where('d.id = ?', $document_id);
    }
    
    static public function getDocumentName($document_id)
    {
      if (empty($document_id))
        return "";
        
      $document = DocumentTable::getInstance()->find($document_id);
      
      if (empty($document))
        return "";        
        
      return $document['name'];
    }
}